<?php
/**
 *驳回需求模型
 *@author shipanpan
 */
class Backup_Model_RejectStory extends Application_Model_Story {
	const CANCLE_HANDLE_RESULT = '取消';
	const PURCHASE_HANDLE_RESULT = '采购';
	const TIMEOUT_CONFIRM_HANDLE_RESULT = '超时未确认';
	const WAIT_CONFIRM_HANDLE_RESULT = '待确认';

	public function __construct() {
		$this->db = $this->db();
		$this->writeDb = $this->db("write_db");
	}

	public function getOneByStoryId(int $rejectStoryId) {
		$where = $this->db->quoteInto("story_id=?", $rejectStoryId);
		return $this->db->fetchRow("select * from b_reject_story where " . $where);
	}

	/**
	 * 取消采购被驳回的需求
	 * @param  int    $rejectStoryId 被驳回需求id
	 * @return [type]                [description]
	 */
	public function cancle(int $rejectStoryId) {
		$storyInfo = $this->getOneByStoryId($rejectStoryId);
		if (!$storyInfo) {
			return $this->_error('需求id为:' . $rejectStoryId . ',的驳回需求不存在！');
		}
		$handler = Model_User::currentLoginUser()->user_name;
		return $this->_updateRejectHandleResult($storyInfo['story_id'], $storyInfo['reject_result'], self::CANCLE_HANDLE_RESULT, $handler);
	}

	/**
	 * 重新采购被驳回的需求
	 * @param  int    $rejectStoryId 被驳回需求id
	 * @return [type]                [description]
	 */
	public function purchase(int $rejectStoryId) {
		$storyInfo = $this->getOneByStoryId($rejectStoryId);
		if (!$storyInfo) {
			return $this->_error('需求id为:' . $rejectStoryId . ',的驳回需求不存在！');
		}
		$handler = Model_User::currentLoginUser()->user_name;
		return $this->_updateRejectHandleResult($storyInfo['story_id'], $storyInfo['reject_result'], self::PURCHASE_HANDLE_RESULT, $handler);
	}

	/**
	 * 超时未确被驳回的需求
	 * @param  int    $rejectStoryId 被驳回需求id
	 * @return [type]                [description]
	 */
	public function timeoutConfirm(int $rejectStoryId) {
		$storyInfo = $this->getOneByStoryId($rejectStoryId);
		if (!$storyInfo) {
			return $this->_error('需求id为:' . $rejectStoryId . ',的驳回需求不存在！');
		}
		return $this->_updateRejectHandleResult($storyInfo['story_id'], $storyInfo['reject_result'], self::TIMEOUT_CONFIRM_HANDLE_RESULT, 'system');
	}

	/**
	 *更新被驳回需求的处理结果
	 * @param  int    $storyId         [description]
	 * @param  [type] $oldRejectResult 更新前的处理结果
	 * @param  [type] $newRejectResult 更新后的处理结果
	 * @return [type]                  [description]
	 */
	private function _updateRejectHandleResult(int $storyId, $oldRejectResult, $newRejectResult, $handler) {
		if ($oldRejectResult != '待处理') {
			return $this->_error('驳回需求的状态不是为待处理！');
		}

		if (!in_array($newRejectResult, [self::CANCLE_HANDLE_RESULT, self::PURCHASE_HANDLE_RESULT, self::TIMEOUT_CONFIRM_HANDLE_RESULT])) {
			return $this->_error('未知的处理结果！');
		}

		$where = $this->writeDb->quoteInto("story_id=?", $storyId);

		return (bool) $this->writeDb->update("b_reject_story", ['reject_result' => $newRejectResult, 'handler' => $handler], $where);
	}
}